package com.heima.search.interceptor;

import com.heima.common.dto.User;

import com.heima.common.util.MediaThreadLocalUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    // 前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取用户的请求头中的userId
        String userIdStr = request.getHeader("userId");
        // 判断用户id不为空
        if (!StringUtils.isEmpty(userIdStr) && !userIdStr.equals("0")) {
            // 转换成为Integer 的用户id
            int userId = Integer.parseInt(userIdStr);
            // 将userId放入到ThreadLocal中,在service中可以随时获取到
            User user = new User();
            user.setUserId(userId);
            MediaThreadLocalUtil.set(user);
        }
        return true;
    }

    // 后置拦截
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        MediaThreadLocalUtil.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
